<template>
	<div class="w-100">
		<dragUpload
			v-loading="loading"
			element-loading-text="Loading..."
			element-loading-background="rgba(122, 122, 122, 0.8)"
			:accept="accept"
			style="width: 100%"
			@file="uploadFile"
		/>
		<ul class="preview-list">
			<li class="preview-item" v-for="(url, index) in fileList" :key="index" :style="{ width: itemWidth }">
				<PreviewImg :src="url" :showFileList="true" @delete="handleDelete(index)"></PreviewImg>
				<!-- <p class="del-btn" @click="handleDelete(index)">删除</p> -->
			</li>
		</ul>
	</div>
</template>

<script setup lang="ts">
import dragUpload from './dragUpload/index.vue'
import PreviewImg from '@/components/AplidCrud/src/AplidUpload/PreviewImg/index.vue'
import apiMod from '@/apiMod'

const emit = defineEmits(['update:modelValue'])
const props = withDefaults(
	defineProps<{
		itemWidth?: string
		dataType?: string
	}>(),
	{
		dataType: 'array',
		itemWidth: '84px',
	}
)
const accept = ''
const percent = ref(0)
const loading = ref(false)
const fileList = ref([])

const onHttpRequest = async (file) => {
	if (fileList.value.length < 9) {
		const form = new FormData()
		form.append('uploadFile', file)
		loading.value = true
		const { data } = await apiMod.uploadFile(form, (progressEvent) => {
			percent.value = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(1))
		})
		loading.value = false
		fileList.value.push(data)
		emit('update:modelValue',props.dataType == 'string' ? fileList.value.toString() : fileList.value)
	} else {
		ElMessage({
			message: '最多上传9张图片',
			type: 'warning',
			duration: 2000,
		})
	}
}

const handleDelete = (index) => {
	fileList.value.splice(index, 1)
	emit('update:modelValue', props.dataType == 'string' ? fileList.value.toString() : fileList.value)
}
const uploadFile = (file) => {
	if (file.length > 0) {
		onHttpRequest(file[0])
	}
}
</script>

<style scoped lang="scss">
.preview-list {
	display: flex;
	flex-flow: row wrap;
	gap: 10px;
	margin-top: 10px;
	.preview-item {
		width: 84px;
		position: relative;
		background: #fff;
		border-radius: 10px;
		margin: 0 6px;

		.del-btn {
			position: absolute;
			top: 10%;
			right: -10px;
			transform: translate(-50%, -50%);
			background: #ffffff7d;
			padding: 2px;
			border-radius: 4px;
			color: #545454;
			font-size: 14px;
			&:hover {
				cursor: pointer;
			}
		}
	}
}
</style>
